package com.gzhryc.shared_device.oem.h5.mng.controllers.agent;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.oem.code.agent.AgentReferrerProfitSynRunnable;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentReferrerBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentReferrerWallet;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentTypeRel;
import com.gzhryc.shared_device.oem.code.agent.dao.models.AgentReferrerCount;
import com.gzhryc.shared_device.oem.code.agent.dao.models.AgentReferrerUser;
import com.gzhryc.shared_device.oem.code.agent.services.AgentReferrerBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentReferrerWalletService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentTypeRelService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentReferrerBusinessConfigSearch;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;

/**
 * 代理介绍人业务配置管理
 */
public class AgentReferrerController {
	
	@Route(value = {"/agent/referrer/list.html"})
    public String list(HttpServletRequest request) {
        return "/agent/referrer/list.html";
    }

    @Route(value = "/agent/referrer/list.data")
    public ListResult<AgentReferrerUser> listData(HttpServletRequest request) {
        ListResult<AgentReferrerUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        AgentReferrerBusinessConfigSearch search = WebUtils.getParameter(request,AgentReferrerBusinessConfigSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(AgentReferrerBusinessConfigService.self().countReferrerUserBySearch(search));
        List<AgentReferrerUser> agentRelationCountList = AgentReferrerBusinessConfigService.self().findReferrerUserBySearch(search
        		,pageNo, pageLimit);
        if (agentRelationCountList != null && agentRelationCountList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(agentRelationCountList);
        }
        return result;
    }
    
    @Route(value = {"/agent/referrer/info.html"})
    public String info(HttpServletRequest request) {
    	Long referrerUserId = WebUtils.getLong(request, "referrerUserId");
    	User user = UserService.self().getById(referrerUserId);
    	WebUtils.setAttribute(request, user);
    	
    	List<AgentReferrerWallet> walletList = AgentReferrerWalletService.self().findJoinByReferrerUserId(referrerUserId);
    	request.setAttribute("walletList", walletList);
        return "/agent/referrer/info.html";
    }
    
    @Route(value = "/agent/referrer/user/list.data")
    public ListResult<Agent> referrerUserListData(HttpServletRequest request) {
        ListResult<Agent> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long referrerUserId = WebUtils.getLong(request, "referrerUserId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        
        List<AgentReferrerCount> referrerCountList = AgentReferrerBusinessConfigService.self()
    			.findReferrerCount(referrerUserId, pageNo, pageLimit);
        
        if(referrerCountList != null && referrerCountList.size() > 0) {
        	List<Long> userIds = new ArrayList<Long>();
        	for(AgentReferrerCount referrerCount:referrerCountList) {
        		userIds.add(referrerCount.getUserId());
        	}
        	
        	List<Agent> agentList = AgentService.self().findJoinByUserIds(userIds);
	        if(agentList != null && agentList.size() > 0) {
	        	List<AgentTypeRel> typeList =  AgentTypeRelService.self().findJoinByUserIds(userIds);
	        	if(typeList != null && typeList.size() > 0) {
	        		for(Agent agent : agentList) {
		        		for(AgentTypeRel type : typeList) {
		        			if(type.getUserId().equals(agent.getUserId())) {
		        				agent.setTypeNames(agent.getTypeNames() + "," + type.getTypeName());
		        			}
		        		}
		        		if(agent.getTypeNames().length() > 0) {
		        			agent.setTypeNames(agent.getTypeNames().substring(1));
		        		}
	        		}
	        	}
	        	result.setCode(DtoConstants.SUCCESS,null);
	        	result.getBody().setData(agentList);
	        }
        }
        return result;
    }
    
    @Route(value = "/agent/referrer/profit/list.data")
    public ListResult<AgentReferrerBusinessConfig> referrerBusiCfgListData(HttpServletRequest request) {
        ListResult<AgentReferrerBusinessConfig> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long referrerUserId = WebUtils.getLong(request, "referrerUserId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        
        AgentReferrerBusinessConfigSearch search = new AgentReferrerBusinessConfigSearch();
        search.setReferrerUserId(referrerUserId);
        List<AgentReferrerBusinessConfig> referrerBusiCfgList = AgentReferrerBusinessConfigService.self().findJoinBySearch(search
        		, pageNo, pageLimit);
        
        if(referrerBusiCfgList != null && referrerBusiCfgList.size() > 0) {
        	List<Long> userIds = new ArrayList<Long>();
        	for(AgentReferrerBusinessConfig referrerBusiCfg : referrerBusiCfgList) {
        		userIds.add(referrerBusiCfg.getUserId());
        	}
        	List<User> userList = UserService.self().findByUserIds(userIds);
        	if(userList != null && userList.size() > 0) {
	        	for(AgentReferrerBusinessConfig referrerBusiCfg : referrerBusiCfgList) {
	        		for(User user : userList) {
	        			if(referrerBusiCfg.getUserId().equals(user.getId())) {
	        				referrerBusiCfg.setUser(user);
	        				break;
	        			}
	        		}
	        	}
        	}
        	
        	result.setCode(DtoConstants.SUCCESS,null);
        	result.getBody().setData(referrerBusiCfgList);
        }
        return result;
    }
    
    
    @Route(value = {"/agent/referrer/profit/syn.html"})
    public String profitSyn(HttpServletRequest request) {
    	List<EBusinessType> businessTypeList = new ArrayList<EBusinessType>();
    	businessTypeList.add(EBusinessType.BXSCN);
    	businessTypeList.add(EBusinessType.BXSCN_SHOP);
    	businessTypeList.add(EBusinessType.CDB);
    	businessTypeList.add(EBusinessType.CDCZ);
    	businessTypeList.add(EBusinessType.PCL);
    	request.setAttribute("businessTypeList", businessTypeList);
        return "/agent/referrer/profit_syn.html";
    }
    
    @Route(value = { "/agent/referrer/profit/syn.do" })
    public AjaxResult doProfitSyn(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"刷新失败，请稍后再试");
        Long referrerUserId = WebUtils.getLong(request, "referrerUserId");
        String businessType = WebUtils.getString(request, "businessType");
        String refreshDate = WebUtils.getString(request, "refreshDate");
        
        if(referrerUserId != null && StringTools.isNotBlank(businessType) && StringTools.isNotBlank(refreshDate)) {
        	try {
	        	String[] strings = refreshDate.split(" - ");
	            if (strings.length == 2) {
	                Date startDate = DateUtils.parseDate(strings[0], "yyyy-MM-dd");
	                Date endDate = DateUtils.parseDate(strings[1], "yyyy-MM-dd");
	                
	                Manager manager = WebUtils.getAttribute(request, SysConstants.LOGIN_MANAGER, Manager.class);
                    OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator( EOperatorType.Manager.index(),manager.getFullName());
                    operateInfo.setOperateNote("后台客服刷新分成");
	                
	                Integer pageNo = 1;
	                Integer pageLimit = 50;
	              
	                AgentReferrerBusinessConfigSearch search = new AgentReferrerBusinessConfigSearch();
	                search.setBusinessType(businessType);
	                search.setReferrerUserId(referrerUserId);

	                List<AgentReferrerBusinessConfig> data = AgentReferrerBusinessConfigService.self()
	                		.findJoinBySearch(search, pageNo, pageLimit);
	                while(data != null && data.size() > 0) {
	                	for(AgentReferrerBusinessConfig item : data) {
	                		AgentReferrerProfitSynRunnable synRunnable = new AgentReferrerProfitSynRunnable(item,startDate
	                				,endDate,operateInfo);
	                		BusyThreadPool.self().execute(synRunnable);
	                	}
	                	pageNo = pageNo + 1;
	                	data =  AgentReferrerBusinessConfigService.self()
		                		.findJoinBySearch(search, pageNo, pageLimit);
	                }
	                
	                result.setCode(DtoConstants.SUCCESS, null);
	            }
        	}catch(ParseException e) {
        		result.setMsg("刷新时间解析失败");
        	}
        }
        return result;
    }
    
    //代理配置介绍人

	@Route(value = "/agent/referrer/busi_cfg/list.data")
    public ListResult<AgentReferrerBusinessConfig> configListData(HttpServletRequest request) {
        ListResult<AgentReferrerBusinessConfig> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        result.getBody().setData(AgentReferrerBusinessConfigService.self().findJoinByUserId(userId));
        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }
	
	@Route(value = { "/agent/referrer/busi_cfg/add.html" })
    public String add(HttpServletRequest request) {
		request.setAttribute("sexList", DefaultEnum.Sex.values());
		List<EBusinessType> businessTypeList = new ArrayList<EBusinessType>();
    	businessTypeList.add(EBusinessType.BXSCN);
    	businessTypeList.add(EBusinessType.BXSCN_SHOP);
    	businessTypeList.add(EBusinessType.CDB);
    	businessTypeList.add(EBusinessType.CDCZ);
    	businessTypeList.add(EBusinessType.PCL);
    	request.setAttribute("businessTypeList", businessTypeList);
        return "/agent/referrer/edit.html";
    }
	
	@Route(value = { "/agent/referrer/busi_cfg/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentReferrerBusinessConfig config = WebUtils.getParameter(request, AgentReferrerBusinessConfig.class);
        User user = WebUtils.getParameter(request,User.class);
        try {
            if(AgentReferrerBusinessConfigService.self().add(config,user)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
	
	@Route(value = { "/agent/referrer/busi_cfg/del.do" })
    public AjaxResult doDelFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Long referrerUserId = WebUtils.getLong(request,"referrerUserId");
        String businessType = WebUtils.getString(request,"businessType");
        try {
            if(AgentReferrerBusinessConfigService.self().deleteByKeys(userId,referrerUserId,businessType)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
